from flask import jsonify, request
from flask.views import MethodView
from app.extensions import db
from app.dbmodel import DevLoginInfo
from flask import current_app
import csv,os,json
from datetime import datetime

#
#        设备登录信息
#           GET方法
# 获取单个设备登录信息GET    /api/devLoginInfo/<int:devLoginInfo_id>
#获取全量设备登录信息GET    /api/devLoginInfo/all
#           POST方法
# 添加单个设备登录信息POST   /api/devLoginInfo/
# 更新单个设备信息POST       /api/devLoginInfo/<int:devLoginInfo_id>
#批量导入设备登录信息POST   /api/devLoginInfo/upload
#           DELETE方法
# 删除设备登录信息DELETE     /api/devLoginInfo/<int:devLoginInfo_id>


class DevLoginInfoAPI(MethodView):

    __methods__ = ["GET", "POST", "DELETE"]

    def get(self, devLoginInfo_id):

        # 全量查询
        if devLoginInfo_id == 'all':
            data = []
            DevLoginInfoAll = DevLoginInfo.query.all()
            count = DevLoginInfo.query.count()
            for item in DevLoginInfoAll:
                item_dict = {'id': item.id, 'DevIp': item.DevIp, 'Port': item.Port, 'User': item.User,
                            'UserPWD': item.UserPWD, 'RootPWD': item.RootPWD, 'DevLoginNote': item.DevLoginNote}
                data.append(item_dict)
            data = {'code': 0, 'msg': '', 'count': count, 'data': data}
            return jsonify(data)

        # 分页查询
        if devLoginInfo_id == None:
            page = request.args.get('page', default=1)
            limit = request.args.get('limit', default=20)
            data = []
            pagination = DevLoginInfo.query.paginate(int(page), int(limit), error_out=False)
            count = DevLoginInfo.query.count()
            for item in pagination.items:
                item_dict = {'id': item.id, 'DevIp': item.DevIp, 'Port': item.Port,
                            'User': item.User, 'UserPWD': item.UserPWD, 'RootPWD': item.RootPWD, 'DevLoginNote': item.DevLoginNote}
                # data.append(item.get_info())
                data.append(item_dict)
            data = {'code': 0, 'msg': '', 'count': count, 'data': data}
            return jsonify(data)
        # 单台查询
        dev = DevLoginInfo.query.get(int(devLoginInfo_id))
        if dev:
            return dev.get_info()
        else:
            return jsonify({"status": "1", "result": "None"})

    def post(self, devLoginInfo_id):
        if devLoginInfo_id == None:
            # 新增设备登录信息
            DevIp = request.form.get('DevIp')
            Port = request.form.get('Port')
            User = request.form.get('User')
            UserPWD = request.form.get('UserPWD')
            RootPWD = request.form.get('RootPWD')
            DevLoginNote = request.form.get('DevLoginNote')
            devLogin_info = DevLoginInfo(
                DevIp=DevIp, Port=Port, User=User, UserPWD=UserPWD, RootPWD=RootPWD, DevLoginNote=DevLoginNote)
            db.session.add(devLogin_info)
            db.session.commit()
            count = DevLoginInfo.query.count()
            if DevLoginInfo.query.get(count) == devLogin_info:
                return jsonify({"code": "0", "status": "0", "result": "this ok"})
            else:
                return jsonify({"code": "1", "status": "1", "result": "error"})
        elif devLoginInfo_id.isdecimal():
            # 更新设备信息
            DevIp = request.form.get('DevIp')
            Port = request.form.get('Port')
            User = request.form.get('User')
            UserPWD = request.form.get('UserPWD')
            RootPWD = request.form.get('RootPWD')
            DevLoginNote = request.form.get('DevLoginNote')
            devLoginInfo = DevLoginInfo.query.get(int(devLoginInfo_id))
            devLoginInfo.DevIp, devLoginInfo.Port, devLoginInfo.User, devLoginInfo.UserPWD, devLoginInfo.RootPWD, devLoginInfo.DevLoginNote, \
                = DevIp, Port, User, UserPWD, RootPWD, DevLoginNote
            info = devLoginInfo.get_info()
            try:
                db.session.commit()
                return jsonify({"code": "0",
                                'msg': 'success',
                                "status": "0",
                                "result": "ok",
                                "data": info})
            except Exception:
                db.session.rollback()
        elif devLoginInfo_id == 'upload':
            # 上传文件，批量新增设备登录信息
            print(current_app.config['UPLOAD_FOLDER'])
            f = request.files.get('file')
            filename_list = f.filename.split('.')
            file_suffix = datetime.utcnow().strftime('%Y%m%d%H%M%S')
            filename_new = '.'.join(
                filename_list[:-1]) + '.' + file_suffix + '.' + filename_list[-1]
            folder = current_app.config['UPLOAD_FOLDER']
            file_path = os.path.join(folder, filename_new)
            f.save(file_path)
            file_size = os.path.getsize(file_path)
            file_path_real = os.path.realpath(file_path)
            count_old = DevLoginInfo.query.count()
            print('count_old:',count_old)
            with open(file_path_real, 'r', encoding='gbk') as file_csv:
                reader = csv.DictReader(
                    file_csv, dialect='excel')  # dialect ='excel'
                for row in reader:
                    print(row)
                    DevIp = row['DevIp']
                    Port = row['Port']
                    User = row['User']
                    UserPWD = row['UserPWD']
                    RootPWD = row['RootPWD']
                    DevLoginNote = row['DevLoginNote']
                    #dev_exist = DevLoginInfo.query.filter(DevLoginInfo.DevIp==DevIp).first()
                    devLogin_info = DevLoginInfo(
                        DevIp=DevIp, Port=Port, User=User, UserPWD=UserPWD, RootPWD=RootPWD, DevLoginNote=DevLoginNote)
                    db.session.add(devLogin_info)
                    # if dev_exist == None:
                    try:
                        #device_info = DevLoginInfo(DevGroup=DevGroup,DevIp=DevIp,DevName=DevName,DevIPv6=DevIPv6,VIPv4=VIPv4,VIPv6=VIPv6,DevIpmi=DevIpmi,DevNote=DevNote)
                        db.session.commit()
                    except Exception:
                        db.session.rollback()
                    finally:
                        # db.session.close()
                        pass
            print("line_num:",reader.line_num)
            num = reader.line_num
            count_new = DevLoginInfo.query.count()
            print('count_old:',count_old)
            print('count_new:',count_new)
            print(count_new - count_old + 1)
            if count_new - count_old + 1 == num:
                return jsonify({"code": "0",
                                "msg": "sucess",
                                "status": "0",
                                "result": "this ok",
                                "data": {
                                    "文件名称": filename_new,
                                    "文件大小": file_size,
                                    "文件路径": file_path_real,
                                    "导入数量": num
                                    # "MD5":""
                                }})
            else:
                return jsonify({'code': '1', 'msg': 'error', "status": "1", "result": "error"})

        return jsonify({'code': "1", 'msg': 'error', "status": "1", "result": "error"})

    def delete(self, devLoginInfo_id):
        if devLoginInfo_id.isdecimal():
            devLoginInfo = DevLoginInfo.query.get(int(devLoginInfo_id))
            info = devLoginInfo.get_info()
            db.session.delete(devLoginInfo)
            try:
                db.session.commit()
                return jsonify({"code": "0",
                                'msg': 'success',
                                "status": "0",
                                "result": "ok",
                                "data": info})
            except Exception:
                db.session.rollback()
            finally:
                pass
        return jsonify({"code": "1", 'msg': 'this api is not exist', "status": "1", "result": "error"})
